from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
import base64
import json

# 随机
gen_random = Random.new

def generate_key():
    # 生成秘钥
    rsakey = RSA.generate(1024)
    with open("rsa.public.pem", mode="wb") as f:
        f.write(rsakey.publickey().exportKey())
    # 私钥，解密用
    with open("rsa.private.pem", mode="wb") as f:
        f.write(rsakey.exportKey())

def encrypt(data):
    # 加密
    with open("rsa.public.pem", mode="r") as f:
        pk = f.read()
        rsa_pk = RSA.importKey(pk)
        rsa = PKCS1_v1_5.new(rsa_pk)
        result = rsa.encrypt(data.encode("utf-8"))
        # 处理成b64方便传输
        b64_result = base64.b64encode(result).decode("utf-8")
        # print(b64_result)
        return b64_result



if __name__ == '__main__':
    generate_key()
    l = {}
    with open('3.json', mode='w', encoding='utf-8') as f:
        for i in range(5):
            name, account, pwd = input(">>>").split(' ')
            # print(name, account, key)
            dic = {}
            dic['account'] = account
            dic['pwd'] = encrypt(pwd)
            l[f'{name}'] = dic

        f.write(json.dumps(l))

